/**
 * Created by Administrator on 2017/4/6 0006.
 */
import React from "react";
import {hashHistory} from "react-router";
import {Modal} from 'antd';
import moment from 'moment';
import ReactKey from "../../../util/ReactKey";
import Select from '../../../common/Select';
import Relay from "react-relay";
import ReactDOM from 'react-dom';
import FindUsersByEnterpriseIdAndPidMutation from "../mutation/FindUsersByEnterpriseIdAndPidMutation";
import GetEnterpriseListMutation from "../mutation/GetEnterpriseListMutation";
import PublishOrderMutation from "../mutation/PublishOrderMutation";
import Util from "../../../util/Util";
export default class AddPartBModal extends React.Component{
    constructor(props){
        super(props);
        this.state={
            visible:false,
            ordernum:'sfaseefew',
            producet:'面料',
            money:1080,
            partbitem:[],
            showaddpartb:false,
            enterpriseList:[],
            linkman:[],
            itemshow:false,
            orderId:"",
            oid:"",
            orderType:"",
            account:"",
        };
        this.linkman = [{text:'请选择联系人',value:'0'}];
        this.enterpriseList=[];
        this.partbitem=[];
        this.chosepartb = 0;
        this.entype = this.props.entype;
        this.deobj={};
        this.orderType_obj={
            "1":"成衣",
            "2":"辅料",
            "3":"面料",
            "4":"印染",
            "5":"纱线",
        };
    }

    componentWillMount(){
        this.setState({
            oid :this.props.oid,
            account : this.props.account,
            orderType :this.props.orderType,
        });
        /*乙方企业*/
        Relay.Store.commitUpdate(
            new GetEnterpriseListMutation({
                serviceType :this.props.ordertype_num,
                // entype :this.props.ordertype_num,
            }),
            {
                onFailure: () => {
                    // console.log("请求失败-乙方企业")
                },
                onSuccess: (response) => {
                    let errorCode = response.getEnterpriseList.data.errorCode;
                    if(errorCode=="0"){
                        let enterpriseList_arr = response.getEnterpriseList.data.enterpriseList;
                        let enterpriseList = [{text:'请选择乙方',value:'0'}];
                        enterpriseList_arr.map((item,index)=>{
                            let enterpriseList_item = {};
                            enterpriseList_item.text = item.enterpriseName;
                            enterpriseList_item.value = item.enterpriseId;
                            enterpriseList.push(enterpriseList_item);
                        });
                        this.enterpriseList = enterpriseList;
                        // this.setState({
                        //     enterpriseList:enterpriseList
                        // });
                    }
                }
            }
        )
    }

    closemodal(){
        this.setState({visible:false});
    }
    addpartbitem(){
        return this.state.partbitem.map((context,index)=>{
            return <PartBItem key={ReactKey.key} context={context} edititem={this.edititem.bind(this)} index={index}
                               ref={'partbitem'+index}
                               saveorderitem = {this.saveorderitem.bind(this)} cancelOrder_item={this.cancelOrder_item.bind(this)} delete_item={this.deletorder.bind(this)}
                              choseem={this.choseem.bind(this)}/>
        });
    }
    /*选择乙方企业操作*/
    choseem(id){
        if(id ==0){
            this.linkman = [{text:'请选择联系人',value:'0'}];
            this.setState({
                linkman:this.linkman
            });
            return;
        }
        this.linkman = [{text:'请选择联系人',value:'0'}];
        Relay.Store.commitUpdate(
            new FindUsersByEnterpriseIdAndPidMutation({
                enterpriseId : id,
                /*销售订单管理权限的用户*/
                pid:'11'
            }),
            {
                onFailure: () => {

                },
                onSuccess: (response) => {

                    let errorCode = response.findUsersByEnterpriseIdAndPid.findUsersByEnterpriseIdAndPid.errorCode;
                    if(errorCode=="0"){
                        let userModelList = response.findUsersByEnterpriseIdAndPid.findUsersByEnterpriseIdAndPid.userModelList;

                        userModelList.map((context,index)=>{
                            this.linkman.push({text:context.name+" "+context.phone,value:context.uid})
                        });
                        this.setState({
                            linkman:this.linkman
                        });
                    }
                }
            }
        )
    }
    /*点击保存*/
    saveorder(){
        if(this.refs.partbname.state.value==0){
            Modal.info({
                title: '提示',
                content: '请选择企业',
            });
            return;
        }
        if(this.refs.linkman.state.value==0){
            Modal.info({
                title: '提示',
                content: '请选择联系人',
            });
            return;
        }

        this.chosepartb = this.refs.partbname.state.value;
        let name =  ReactDOM.findDOMNode(this.refs.partbname).selectedOptions[0].innerHTML;
        let namevalue = this.refs.partbname.state.value;
        let linkman = ReactDOM.findDOMNode(this.refs.linkman).selectedOptions[0].innerHTML;
        let linkmanvalue = this.refs.linkman.state.value;
        let deobj = {'text':name,'value':this.chosepartb};
        this.deobj = deobj;
        let enterpriseList = this.enterpriseList;
        let tempindex = -1;
        enterpriseList.map((temp, index)=> {
            if ( JSON.stringify(deobj) == JSON.stringify(temp)) {
                tempindex = index;
            }
        });
        if (tempindex != -1) {
            enterpriseList.splice(tempindex, 1);
        }
        // let partbitem = [];
        this.partbitem.push({'name':name,'namevalue':namevalue,'linkman':linkman,'linkmanvalue':linkmanvalue,'linkmanlist':this.linkman});
        this.setState({
            partbitem:this.partbitem,
            showaddpartb:false,
            // enterpriseList:enterpriseList
        });
        this.enterpriseList = enterpriseList;
        // console.log(this.enterpriseList)
        // console.log(partbitem)
    }

    saveorderitem(context,index){
        let deobj = {'text':context.name,'value':context.namevalue};
        this.deobj = deobj;
        let enterpriseList = this.enterpriseList;
        let tempindex = -1;
        enterpriseList.map((temp, index)=> {
            if ( JSON.stringify(deobj) == JSON.stringify(temp)) {
                tempindex = index;
            }
        });
        if (tempindex != -1) {
            enterpriseList.splice(tempindex, 1);
        }


        this.enterpriseList = enterpriseList;
        this.partbitem.splice(index,1,context);
        this.setState({
            partbitem:this.partbitem,
            showaddpartb:false,
            itemshow:false
        });
    }

    cancelOrder_item(){
        this.setState({
            itemshow:false
        });
    }
    /*删除*/
    deletorder(namevalue){
        let partbitem = this.partbitem;
        let enterpriseList = this.enterpriseList;
        partbitem = partbitem.filter((item)=>{
            if(namevalue == item.namevalue){
               enterpriseList.push({text:item.name,value:item.namevalue});
           }
           return namevalue == item.value;
        });
        this.enterpriseList = enterpriseList;
        this.partbitem = partbitem;
        this.setState({
            partbitem:partbitem
        },()=>{
            // console.log(this.state.partbitem)
            // console.log(this.enterpriseList)
        })
    }
    /*取消*/
    cancelOrder(){
        this.setState({
            showaddpartb:false
        });
    }
    /*编辑*/
    edititem(index){
        let partbitem = this.state.partbitem;
        let obj = partbitem[index];
        let envalue = obj.namevalue;
        let linkmanvalue = obj.linkmanvalue;
        let enterpriseList = this.enterpriseList;
        enterpriseList.push(this.deobj);
        this.setState({
            itemshow:true
        },()=>{
            this.state.partbitem.map((context,i)=>{
                this.refs['partbitem'+i].setState({
                    showeidt:false
                });
            });
            this.refs['partbitem'+index].setState({
                isedit : true,
                enterpriseList:enterpriseList,
                linkman:this.linkman,
                defaultpartbname:envalue,
                defaultlinkman:linkmanvalue
            });
        });
    }
    /*添加乙方弹框*/
    addpartb(){
        return(
            <div className="order_modal_addpartb_partb_div">
                <p className="order_modal_addpartb_partb_pb">
                    乙方：
                    <Select oArr={this.enterpriseList}  style={{marginTop:"20px",width:290,height:27,display:"block",borderColor:"#36b3b3"}}
                            onselectchose={this.choseem.bind(this)} ref={"partbname"}/>
                </p>

                <p className="order_modal_addpartb_partb_pp">
                    联系人：
                    <Select oArr={this.linkman}  style={{marginTop:"20px",width:290,height:27,display:"block",border:"1px lolid #36b3b3",borderColor:"#36b3b3"}} key={ReactKey.key} ref={'linkman'}/>

                </p>

                <button className="order_modal_addpartb_buttonup" onClick={this.saveorder.bind(this)}>保存</button>
                <button className="order_modal_addpartb_buttoncn" onClick={this.cancelOrder.bind(this)}>取消</button>
            </div>
        );
    }
    /*添加乙方*/
    showaddpartb(){
        this.setState({
            showaddpartb:true,
        });
    }
    /*点击发布*/
    publish(){
        let partBs = [];
        if(this.state.partbitem.length == 0){
            Modal.info({
                title: '提示',
                content: '请添加乙方企业',
            });
            return;
        }
        this.state.partbitem.map((item,index)=>{
            let linkman = item.linkman.split(/\s/g);
            let partBs_item = {};
            partBs_item.enId = item.namevalue;
            partBs_item.toUserId = item.linkmanvalue;
            partBs_item.enName = item.name;
            partBs_item.name = linkman[0];
            partBs_item.phone = linkman[1];
            partBs.push(partBs_item);
        });
        Relay.Store.commitUpdate(
            new PublishOrderMutation({
                orderId:this.state.orderId,
                partBs:JSON.stringify(partBs),
            }),
            {
                onFailure: () => {
                    // console.log("请求失败-点击发布")
                },
                onSuccess: (response) => {
                    let errorCode = response.publishOrder.publishOrder.errorCode;
                    let orderId = response.publishOrder.publishOrder.order["oid"];
                    if(errorCode=="0"){
                        if(this.props.ordertype_num == "1"){
                            hashHistory.push("/orderdetailgms/"+orderId)
                        }if(this.props.ordertype_num == "3"){
                            hashHistory.push("/orderdetailcloth/"+orderId)
                        }if(this.props.ordertype_num == "5"){
                            hashHistory.push("/orderdetailyarn/"+orderId)
                        }if(this.props.ordertype_num == "4"){
                            hashHistory.push("/orderdetailprint/"+orderId)
                        }if(this.props.ordertype_num == "2"){
                            hashHistory.push("/orderdetailraw/"+orderId)
                        }
                    }
                }
            }
        )
    }

    render(){
        return (
            <Modal visible={this.state.visible} footer={null} onCancel={this.closemodal.bind(this)} title={'添加乙方'}>
                <div style={{marginTop:30,marginLeft:62}}>订单编号：{this.state.oid}</div>
                <div style={{marginTop:20,marginLeft:62}}>采购商品：{this.orderType_obj[this.state.orderType]}</div>
                <div style={{marginTop:20,marginLeft:62}}>订单金额：￥{this.state.account/100}元</div>
                {
                    this.addpartbitem()
                }
                {
                    this.state.showaddpartb
                    ?
                        this.addpartb()
                        :
                        this.state.itemshow?
                            null
                            :
                            <div>
                                <div className="order_modal_addpartb_add" onClick={this.showaddpartb.bind(this)}>+添加乙方</div>
                                <div className="order_modal_addpartb_add" onClick={this.publish.bind(this)}>发布</div>
                            </div>
                }
            </Modal>
        )
    }
}

/*乙方企业item*/
class PartBItem extends React.Component{
    constructor(props){
        super(props);
        this.state={
            isedit:false,
            enterpriseList:[],
            linkman:this.props.context.linkmanlist,
            defaultpartbname:0,
            defaultlinkman:0,
            showeidt:true,
            context: this.props.context
        };
        this.linkman = [{text:'请选择联系人',value:'0'}];
    }



    editen(){
        this.props.edititem(this.props.index);
    }
    delete_item(){
        this.props.delete_item(this.props.context.namevalue);
    }
    saveorder(){
        // if(this.refs.partbname.state.value==0){
        //     Modal.info({
        //         title: '提示',
        //         content: '请选择企业',
        //     });
        //     return;
        // }
        //
        // if(this.refs.linkman.state.value==0){
        //     Modal.info({
        //         title: '提示',
        //         content: '请选择联系人',
        //     });
        //     return;
        // }
        let newcontext = this.state.context;

        let name =  ReactDOM.findDOMNode(this.refs.partbname).selectedOptions[0].innerHTML;
        let namevalue = this.refs.partbname.state.value || this.refs.partbname.state.defaultValue;
        let linkman = ReactDOM.findDOMNode(this.refs.linkman).selectedOptions[0].innerHTML;
        let linkmanvalue = this.refs.linkman.state.value||this.refs.linkman.state.defaultValue;;
        newcontext.name = name;
        newcontext.namevalue = namevalue;
        newcontext.linkman = linkman;
        newcontext.linkmanvalue = linkmanvalue;
        newcontext.linkmanlist = this.state.linkman;
        // console.warn(this.state.linkman)
        this.props.saveorderitem(newcontext,this.props.index);
    }

    cancelOrder(){
        this.props.cancelOrder_item(this.props.index);
    }

    choseem(id){
        if(id ==0){
            this.linkman = [{text:'请选择联系人',value:'0'}];
            this.setState({
                linkman:this.linkman
            });
            return;
        }
        this.linkman = [{text:'请选择联系人',value:'0'}];
        Relay.Store.commitUpdate(
            new FindUsersByEnterpriseIdAndPidMutation({
                enterpriseId : id,
                /*销售订单管理权限的用户*/
                pid:'11'
            }),
            {
                onFailure: () => {

                },
                onSuccess: (response) => {

                    let errorCode = response.findUsersByEnterpriseIdAndPid.findUsersByEnterpriseIdAndPid.errorCode;
                    if(errorCode=="0"){
                        let userModelList = response.findUsersByEnterpriseIdAndPid.findUsersByEnterpriseIdAndPid.userModelList;

                        userModelList.map((context,index)=>{
                            this.linkman.push({text:context.name+" "+context.phone,value:context.uid})
                        });
                        this.setState({
                            linkman:this.linkman
                        });
                    }
                }
            }
        )



    }

    addpartb(){
        return(
            <div className="order_modal_addpartb_partb_div" key={React.key}>
                <p style={{width: 1094, height: 58, paddingLeft: "26px", lineHeight: "58px",position:"relative",marginTop:"10px"}}>
                    乙方：
                    <Select oArr={this.state.enterpriseList}  style={{marginTop:"20px",width:290,height:27,display:"block",borderColor:"#36b3b3"}}
                            onselectchose={this.choseem.bind(this)} ref={"partbname"}
                            defaultValue={this.state.defaultpartbname}/>
                </p>

                <p style={{width: 1094, height: 58, paddingLeft: "14px", lineHeight: "58px",position:"relative",marginTop:"-8px"}}>
                    联系人：
                    <Select oArr={this.state.linkman}  style={{marginTop:"20px",width:290,height:27,display:"block",border:"1px lolid #36b3b3",borderColor:"#36b3b3"}}
                            key={ReactKey.key} ref={'linkman'} defaultValue={this.state.defaultlinkman}/>

                </p>

                <button className="order_modal_addpartb_buttonup" onClick={this.saveorder.bind(this)}>
                    保存</button>
                <button className="order_modal_addpartb_buttoncn" onClick={this.cancelOrder.bind(this)}>取消</button>
            </div>
        );
    }

    render(){
        if(this.state.isedit){
            return(
                this.addpartb()
            );
        }else{
            return(
                <div className="order_modal_addpartb_div">
                    <div style={{marginTop:30,marginLeft:86}}>乙方：{this.state.context.name}</div>
                    <div style={{marginTop:20,marginLeft:74}}>联系人：{this.state.context.linkman}</div>
                    <div className={this.state.showeidt?"order_modal_addpartb_edit":"order_modal_addpartb_edit_none"} onClick={this.editen.bind(this)}>编辑</div>
                    <div className="order_modal_addpartb_del" onClick={this.delete_item.bind(this)}>删除</div>
                </div>
            );
        }
    }
}
